package com.xwm93up.threadsecurity;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * @Description: 同步方法
 * @Author: xwm93up
 * @Since: 2022/5/13 17:43
 */
public class ThreadSynchroniazedMethodSecurity {
    static int tickets = 10;

    class SellTickets implements Runnable{

        @Override
        public void run() {
            // 同步方法
            while (tickets > 0) {
                syncMethod();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (tickets <= 0) {
                    System.out.println(Thread.currentThread().getName() + "--->售票结束");
                }
            }
        }

        synchronized void syncMethod() {
            if (tickets <= 0) {
                return;
            }
            System.out.println(Thread.currentThread().getName() + "---->售出第" + tickets +"票");
            tickets--;
        }
    }

    public static void main(String[] args) {
        final SellTickets sellTickets = new ThreadSynchroniazedMethodSecurity().new SellTickets();
        Thread thread1 = new Thread(sellTickets, "1号窗口");
        Thread thread2 = new Thread(sellTickets, "2号窗口");
        Thread thread3 = new Thread(sellTickets, "3号窗口");
        Thread thread4 = new Thread(sellTickets, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}
